/**
 * ------------------------------------------------------
 *  fetch请求的封装处理
 * ------------------------------------------------------
 *
 * Note: .
 */

import { getToken, removeToken } from "./token"
import { API_TIMEOUT, DATA_API } from "@/config/constants"
import { formDataToJSON, toQueryString } from "./helper"

/**
 * 封装fetch请求
 * @param {object} config 请求配置
    config = {
      url: string api路由(必填)
      method: string 提交模式
      headers: object 请求头信息
      data: object 提交（POST）数据
      params: object api url参数
    }
 * 
 */
function requestFetch (config){
    const token = getToken()
    const head = {
      'Content-Type': 'application/json'
    }
    if(token){
      head['Authorization'] = `Bearer ${token}`      
    }
    const defaultConfig = {
      url:'',
      method:'GET',
      headers:head,
    }
    const Opt = Object.assign({}, defaultConfig, config)
    console.log(Opt)
    if('data' in Opt){
      Opt.body = typeof Opt.data ==='object' ? formDataToJSON(Opt.data) :{}
    }
    return fetch(DATA_API + Opt.url + (('params' in Opt) ? '?'+toQueryString(Opt.params):''),
      Opt
    )
  .then((response)=>response.json())
  .catch(error=>console.error('提交遇到错误：',error))
}

export { requestFetch }
